<meta charset='utf8' />
<canvas id='canvas' width='256px' height='256px'></canvas>
<script type="text/javascript" src='../js/vector.js'></script>
<script type="text/javascript" src='../js/ray.js'></script>
<script type="text/javascript" src='../js/substance.js'></script>
<script type="text/javascript" src='../js/perspectiveCamera.js'></script>
<script type="text/javascript" src='../js/color.js'></script>
<script type="text/javascript" src='../js/material.js'></script>
<script type="text/javascript" src='../js/union.js'></script>
<script type="text/javascript">
	function renderDepth(canvas, scene, camera, maxDepth) {
		var w = canvas.width;
		var h = canvas.height;
		var ctx = canvas.getContext('2d');
		ctx.fillRect(0, 0, w, h);
		var imgData = ctx.getImageData(0, 0, w, h);
		var pixels = imgData.data;

		scene.initialize();
		camera.initialize();

		var i = 0;
		var sx, sy, ray, result, depth;
		for(var y = 0; y < h; y++){
			sy = 1 - y / h;
			for(var x = 0; x < w; x++){
				sx = x / w;
				ray = camera.generateRay(sx, sy);
				var color = rayTraceRecursive(scene, ray, maxReflect);
				pixels[i] = color.r * 255;
				pixels[i + 1] = color.g * 255;
				pixels[i + 2] = color.b * 255;
				pixels[i + 3] = 255;
				i += 4;
			}
		}
		ctx.putImageData(imgData, 0, 0);
	}
	function rayTraceRecursive(scene, ray, maxReflect) {
		var result = scene.intersect(ray);
		if(result.geometry) {
			var reflectiveness = result.geometry.material.reflectiveness;
			var color = result.geometry.material.sample(ray, result.position, result.normal);
			color = color.multiply(1 - reflectiveness);
			if(maxReflect > 0) {
				var r = result.normal.multiply(-2 * result.normal.dot(ray.direction)).add(ray.direction);
				ray = new Ray3(result.position, r);
				var reflectedColor = rayTraceRecursive(scene, ray, maxReflect - 1);
				color = color.add(reflectedColor.multiply(reflectiveness));
			}
			return color;
		} else {
			return Color.black;
		}
	}
	var maxReflect = 4;
	var plane = new Plane(new Vector3(0, 1, 0), 0);
	plane.material = new CheckerMaterial(0.1, 0.5);
	var sphere1 = new Sphere(new Vector3(-10, 10, -10), 10);
	sphere1.material = new PhoneMaterial(Color.red, Color.white, 16, 0.25);
	var sphere2 = new Sphere(new Vector3(10, 10, -10), 10);
	sphere2.material = new PhoneMaterial(Color.green, Color.white, 16, 0.25);
	var camera = new PerspectiveCamera(new Vector3(0, 10, 15), new Vector3(0, 0, -1), new Vector3(1, 0, 0), 90);

	var lightDir = new Vector3(1, 1, 1).normalize();
	var lightColor = Color.white;
	var start = new Date().getTime();
	renderDepth(canvas, new Union([plane, sphere1, sphere2]), camera, 20);
	var end = new Date().getTime();
	console.log(end - start);
</script>